# -*- coding:utf-8 -*-

## =====================================================================
## Copyright (C) 2007-2011  Jean-Philippe GOLAY
##
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
## GNU General Public License for more details.
##
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
## =====================================================================


from Tkinter import *
import Pmw
from tkMessageBox import *

from Persistance import *
from iCalendar import CalendarGUI
from iTime import TimePopupGUI
from iNotes import NotesGUI
from iPlace import PlaceListGUI
from iStaff import StaffListGUI
from iProduct import ProductListGUI
from iStay import StayListGUI

class OcupancyGUI(Toplevel):
	def __init__(self, parent=None, balloon=None, path=None, log=None):
		Toplevel.__init__(self, parent)
		self.parent=parent
		self.grab_set()
		self.transient(self.master)
		self.resizable(width=False, height=False)
		self.title(u"Planning d'occupation de la résidence")
		self.balloon=balloon
		self.imgSearch=PhotoImage(file="img/search_icon.gif")
		self.imgNotes=PhotoImage(file="img/edit.gif")
		self.imgSave=PhotoImage(file="img/save_icon.gif")
		self.imgDelete=PhotoImage(file="img/delete_icon.gif")
		self.imgCalendar=PhotoImage(file="img/calendar.gif")
		self.imgTime=PhotoImage(file="img/time_icon.gif")
		self.hoursListCB = Glob.HOURS_LIST
		self.minutesListCB = Glob.MINUTES_LIST
		self.path=path
		self.log=log
		# Afficher un icon personnalisé
		try:
			if os.name =="posix":
				img = PhotoImage(file=self.path+"/icons/Ocupancy-icon.gif")
				self.tk.call("wm", "iconphoto", self._w, img)
			else:
				self.iconbitmap(default=self.path+"/icons/Ocupancy-icon.gif")
		except TclError:
			self.log.warning("Le window manager ne supporte pas l'icône que je veux lui mettre...")
		self.log.info("\tOcupancyGUI\tStart")
		self.makeOcupancy()

	# DEBUT de la gestion du module Ocupancy ------------------------------------------------------------------------------------------------------
	def clearFieldOcupancy(self):
		# Mise a zéro des champs
		self.ocupancyValues[0].set("")
		self.ocupancyValues[1].set("")
		self.ocupancyValues[2].set("")
		self.ocupancyValues[3].set("")
		self.ocupancyValues[4].set("")
		self.ocupancyValues[5].set("")
		self.ocupancyValues[6].set("")
		self.ocupancyValues[7].set("")
		self.ocupancyValues[8].set("")
		self.ocupancyValues[9].set("")
		self.ocupancyValues[10].set("")
		self.ocupancyValues[11].set("")
		# Remise à zéro des ComboBox
		self.hourInOcupancyCB.selectitem(0)
		self.minInOcupancyCB.selectitem(0)
		self.hourOutOcupancyCB.selectitem(0)
		self.minOutOcupancyCB.selectitem(0)
		self.ocupancyHourIn=StringVar()
		self.ocupancyMinuteIn=StringVar()
		self.ocupancyHourOut=StringVar()
		self.ocupancyMinuteOut=StringVar()
		self.listObject=[Place, Stay, Product, Staff, Staff, Staff, Staff]

	def selectOcupancy(self, event):
		if self.listOcupancy.get(0)!="":
			result = Ocupancy.select(Ocupancy.q.id==self.idListOcupancy[int(self.listOcupancy.curselection()[0])])
			for row in result:
				self.selectedOcupancy = row
			self.listObject[0]=self.selectedOcupancy.place
			self.listObject[1]=self.selectedOcupancy.stay
			self.listObject[2]=self.selectedOcupancy.product
			self.listObject[3]=self.selectedOcupancy.checkInBy
			self.listObject[4]=self.selectedOcupancy.checkOutBy
			self.listObject[5]=self.selectedOcupancy.invantoryInBy
			self.listObject[6]=self.selectedOcupancy.invantoryOutBy
			self.ocupancyValues[0].set(self.listObject[0].company)
			self.ocupancyValues[1].set(self.listObject[1].contact)
			self.ocupancyValues[2].set(self.listObject[2].number+" - "+self.listObject[2].designation)
			if self.selectedOcupancy.checkInBy != None:self.ocupancyValues[5].set(self.listObject[3].fname+" - "+self.listObject[3].lname)
			if self.selectedOcupancy.checkOutBy != None:self.ocupancyValues[8].set(self.listObject[4].fname+" - "+self.listObject[4].lname)
			if self.selectedOcupancy.invantoryInBy != None:self.ocupancyValues[6].set(self.listObject[5].fname+" - "+self.listObject[5].lname)
			if self.selectedOcupancy.invantoryOutBy != None:self.ocupancyValues[7].set(self.listObject[6].fname+" - "+self.listObject[6].lname)
			if self.selectedOcupancy.notes != None:self.ocupancyValues[11].set(self.selectedOcupancy.notes)
			if self.selectedOcupancy.checkIn != None:
				# Affichage de la date de Début (self.selectedOcupancy .dateIn)
				self.ocupancyValues[3].set(self.selectedOcupancy.checkIn.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Début dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedOcupancy.checkIn.strftime("%H"): self.hourInOcupancyCB.selectitem(count)
					count+=1
				# Affichage des minutes de Début dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedOcupancy.checkIn.strftime("%M"): self.minInOcupancyCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Début
				self.ocupancyHourIn.set(self.selectedOcupancy.checkIn.strftime("%H"))
				self.ocupancyMinuteIn.set(self.selectedOcupancy.checkIn.strftime("%M"))
			if self.selectedOcupancy.checkOut != None:
				# Affichage de la date de Fin (self.selectedOcupancy .dateOut)
				self.ocupancyValues[9].set(self.selectedOcupancy.checkOut.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Fin dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedOcupancy.checkOut.strftime("%H"): self.hourOutOcupancyCB.selectitem(count)
					count+=1
				# Affichage des minutes de Fin dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedOcupancy.checkOut.strftime("%M"): self.minOutOcupancyCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Fin
				self.ocupancyHourOut.set(self.selectedOcupancy.checkOut.strftime("%H"))
				self.ocupancyMinuteOut.set(self.selectedOcupancy.checkOut.strftime("%M"))
			# activation du bouton supprimer
			self.deleteOcupancyBt.config(state=NORMAL)

	def set(self, e):
			result = Ocupancy.select(Ocupancy.q.id==int(e.ocupancyID))
			for row in result:
				self.selectedOcupancy = row
			self.listObject[0]=self.selectedOcupancy.place
			self.listObject[1]=self.selectedOcupancy.stay
			self.listObject[2]=self.selectedOcupancy.product
			self.listObject[3]=self.selectedOcupancy.checkInBy
			self.listObject[4]=self.selectedOcupancy.checkOutBy
			self.listObject[5]=self.selectedOcupancy.invantoryInBy
			self.listObject[6]=self.selectedOcupancy.invantoryOutBy
			self.ocupancyValues[0].set(self.listObject[0].company)
			self.ocupancyValues[1].set(self.listObject[1].contact)
			self.ocupancyValues[2].set(self.listObject[2].number+" - "+self.listObject[2].designation)
			if self.selectedOcupancy.checkInBy != None:self.ocupancyValues[5].set(self.listObject[3].fname+" - "+self.listObject[3].lname)
			if self.selectedOcupancy.checkOutBy != None:self.ocupancyValues[8].set(self.listObject[4].fname+" - "+self.listObject[4].lname)
			if self.selectedOcupancy.invantoryInBy != None:self.ocupancyValues[6].set(self.listObject[5].fname+" - "+self.listObject[5].lname)
			if self.selectedOcupancy.invantoryOutBy != None:self.ocupancyValues[7].set(self.listObject[6].fname+" - "+self.listObject[6].lname)
			if self.selectedOcupancy.notes != None:self.ocupancyValues[11].set(self.selectedOcupancy.notes)
			if self.selectedOcupancy.checkIn != None:
				# Affichage de la date de Début (self.selectedOcupancy .dateIn)
				self.ocupancyValues[3].set(self.selectedOcupancy.checkIn.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Début dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedOcupancy.checkIn.strftime("%H"): self.hourInOcupancyCB.selectitem(count)
					count+=1
				# Affichage des minutes de Début dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedOcupancy.checkIn.strftime("%M"): self.minInOcupancyCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Début
				self.ocupancyHourIn.set(self.selectedOcupancy.checkIn.strftime("%H"))
				self.ocupancyMinuteIn.set(self.selectedOcupancy.checkIn.strftime("%M"))
			if self.selectedOcupancy.checkOut != None:
				# Affichage de la date de Fin (self.selectedOcupancy .dateOut)
				self.ocupancyValues[9].set(self.selectedOcupancy.checkOut.strftime("%d/%m/%Y"))
				# Affichage de l'heure de Fin dans la ComboBox 
				count = 0
				for h in self.hoursListCB:
					if h == self.selectedOcupancy.checkOut.strftime("%H"): self.hourOutOcupancyCB.selectitem(count)
					count+=1
				# Affichage des minutes de Fin dans la ComboBox
				count = 0
				for m in self.minutesListCB:
					if m == self.selectedOcupancy.checkOut.strftime("%M"): self.minOutOcupancyCB.selectitem(count)
					count+=1
				# Mise à jour des variables heure et minutes de Fin
				self.ocupancyHourOut.set(self.selectedOcupancy.checkOut.strftime("%H"))
				self.ocupancyMinuteOut.set(self.selectedOcupancy.checkOut.strftime("%M"))
			# activation du bouton supprimer
			self.deleteOcupancyBt.config(state=NORMAL)

	def setDateTime(self, e):
		self.ocupancyValues[3].set(e.date)
		result=Product.select(Product.q.id==int(e.productID))
		for row in result:
			self.listObject[2]=row
			self.ocupancyValues[2].set(self.listObject[2].number+" - "+self.listObject[2].designation)
			self.listObject[0]=self.listObject[2].place
			self.ocupancyValues[0].set(self.listObject[0].company)
		result=Stay.select(Stay.q.id==int(e.stayID))
		for row in result:
			self.listObject[1]=row
			self.ocupancyValues[1].set(self.listObject[1].contact)

	def searchOcupancy(self, event=None):
		if self.searchOcupancyValue.get() != "":
			self.listOcupancy.delete(0,END)
			self.idListOcupancy = []
			result = Ocupancy.select(Ocupancy.q.place.startswith(self.searchOcupancyValue.get().encode("utf-8")), orderBy=Ocupancy.q.place)
			for row in result:
				if row.checkIn != None:
					self.listOcupancy.insert(END, row.place.company+" - "+row.product.number+" - "+str(row.stay)+" PR "+row.stay.checkIn.strftime("%d/%m/%Y %H:%M")+" AR "+row.checkIn.strftime("%d/%m/%Y %H:%M"))
				else:
					self.listOcupancy.insert(END, row.place.company+" - "+row.product.number+" - "+str(row.stay)+" PR "+row.stay.checkIn.strftime("%d/%m/%Y %H:%M")+" AR non")
				self.idListOcupancy.append(row.id)
		else:
			self.listOcupancy.delete(0,END)
			self.idListOcupancy = []
			result = Ocupancy.select(orderBy=Ocupancy.q.place)
			for row in result:
				if row.checkIn != None:
					self.listOcupancy.insert(END, row.place.company+" - "+row.product.number+" - "+str(row.stay)+" PR "+row.stay.checkIn.strftime("%d/%m/%Y %H:%M")+" AR "+row.checkIn.strftime("%d/%m/%Y %H:%M"))
				else:
					self.listOcupancy.insert(END, row.place.company+" - "+row.product.number+" - "+str(row.stay)+" PR "+row.stay.checkIn.strftime("%d/%m/%Y %H:%M")+" AR non")
				self.idListOcupancy.append(row.id)

	def makeOcupancy(self):
		leftFrame = Frame(self)
		# Fiche Occupation  (présentation colonne de gauche)
		Label(leftFrame, text=u"Occupation").pack(side=TOP, fill=X)
		# Création des champs a renseigner pour un object Ocupancy
		ocupancyLabels = (u"Résidence", u"Séjour associé", u"Produit assigné", u"Arrivée (date)", u"Arrivée (heure)", u"Arrivée par", u"Inv. entrée par", u"Inv. sortie par", u"Départ par", u"Départ (date)", u"Départ (heure)", u"Notes")
		self.ocupancyValues = [StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar(), StringVar()]
		count = 0
		for name in ocupancyLabels:
			f = Frame(leftFrame)
			Label(f, width=16, text=name, anchor=W).pack(side=LEFT)
			if count == 0: # Place
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myPlace=Button(f,  image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListPlace(x), padx=4, pady=1)
				myPlace.pack(side=RIGHT)
				self.balloon.bind(myPlace, u"Choisir une Résidence")
			elif count == 1: # Stay
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myStay=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListStay(x), padx=4, pady=1)
				myStay.pack(side=RIGHT)
				self.balloon.bind(myStay, u"Choisir un Séjour")
			elif count == 2: # Product
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myProduct=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListProduct(x), padx=4, pady=1)
				myProduct.pack(side=RIGHT)
				self.balloon.bind(myProduct, u"Choisir un Produit")
			elif count == 3: # ChekIn date
				Entry(f, textvariable=self.ocupancyValues[count], width=20).pack(side=LEFT, fill=X)
				myCal1=Button(f, image=self.imgCalendar, command=lambda x=self.ocupancyValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal1.pack(side=LEFT)
				self.balloon.bind(myCal1, u"Calendrier")
			elif count == 4: # ChekIn hour
				hStartLb1=Label(f, width=2, text="H", anchor=W)
				hStartLb1.pack(side=LEFT)
				self.balloon.bind(hStartLb1, u"Heure")
				self.hourInOcupancyCB=Pmw.ComboBox(f, selectioncommand=self.ocupancyHourIn, scrolledlist_items=self.hoursListCB, listheight=100)
				self.hourInOcupancyCB._entryfield._entryFieldEntry.config( width = 3)
				self.hourInOcupancyCB.pack(side=LEFT)
				mStartLb1=Label(f, width=3, text="mn", anchor=W)
				mStartLb1.pack(side=LEFT)
				self.balloon.bind(mStartLb1, u"minutes")
				self.minInOcupancyCB=Pmw.ComboBox(f, selectioncommand=self.ocupancyMinuteIn, scrolledlist_items=self.minutesListCB, listheight=100)
				self.minInOcupancyCB._entryfield._entryFieldEntry.config( width = 3)
				self.minInOcupancyCB.pack(side=LEFT)
				# Menu Time
				myTime1=Button(f, image=self.imgTime, padx=1, pady=1)
				myTime1.pack(side=RIGHT)
				myTime1.bind("<ButtonRelease-1>",self.ctrlTimeNow1)
				self.balloon.bind(myTime1, u"Séléctionner une heure")
			elif count == 5: # checkInBy
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myCheckInBy=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListStaff(x,3), padx=4, pady=1)
				myCheckInBy.pack(side=RIGHT)
				self.balloon.bind(myCheckInBy, u"Séléctionner un employé")
			elif count == 6: # invantoryInBy
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myInventoryInBy=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListStaff(x,5), padx=4, pady=1)
				myInventoryInBy.pack(side=RIGHT)
				self.balloon.bind(myInventoryInBy, u"Séléctionner un employé")
			elif count == 7: # invantoryOutBy
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myInventoryOutBy=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListStaff(x,6), padx=4, pady=1)
				myInventoryOutBy.pack(side=RIGHT)
				self.balloon.bind(myInventoryOutBy, u"Séléctionner un employé")
			elif count == 8: # checkOutBy
				Entry(f, textvariable=self.ocupancyValues[count], width=20, state=DISABLED, bd=0, disabledforeground="black").pack(side=LEFT, fill=X)
				myCheckOutBy=Button(f, image=self.imgSearch, command=lambda x=self.ocupancyValues[count]:self.ctrlListStaff(x,4), padx=4, pady=1)
				myCheckOutBy.pack(side=RIGHT)                   
				self.balloon.bind(myCheckOutBy, u"Séléctionner un employé")
			elif count == 9: # ChekOut date
				Entry(f, textvariable=self.ocupancyValues[count], width=20).pack(side=LEFT, fill=X)
				myCal2=Button(f, image=self.imgCalendar, command=lambda x=self.ocupancyValues[count]:self.ctrlCalendar(x), padx=4, pady=1)
				myCal2.pack(side=LEFT)
				self.balloon.bind(myCal2, u"Calendrier")
			elif count == 10: # ChekOut hour
				hStartLb2=Label(f, width=2, text="H", anchor=W)
				hStartLb2.pack(side=LEFT)
				self.balloon.bind(hStartLb2, u"Heure")
				self.hourOutOcupancyCB=Pmw.ComboBox(f, selectioncommand=self.ocupancyHourOut, scrolledlist_items=self.hoursListCB, listheight=100)
				self.hourOutOcupancyCB._entryfield._entryFieldEntry.config( width = 3)
				self.hourOutOcupancyCB.pack(side=LEFT)
				mStartLb2=Label(f, width=3, text="mn", anchor=W)
				mStartLb2.pack(side=LEFT)
				self.balloon.bind(mStartLb2, u"minutes")
				self.minOutOcupancyCB=Pmw.ComboBox(f, selectioncommand=self.ocupancyMinuteOut, scrolledlist_items=self.minutesListCB, listheight=100)
				self.minOutOcupancyCB._entryfield._entryFieldEntry.config( width = 3)
				self.minOutOcupancyCB.pack(side=LEFT)
				# Menu Time
				myTime2=Button(f, image=self.imgTime, padx=1, pady=1)
				myTime2.pack(side=RIGHT)
				myTime2.bind("<ButtonRelease-1>",self.ctrlTimeNow2)
				self.balloon.bind(myTime2, u"Séléctionner une heure")
			elif count == 11: # Notes
				Entry(f, textvariable=self.ocupancyValues[count], width=20).pack(side=LEFT, fill=X)
				myNotes=Button(f, image=self.imgNotes, command=lambda x=self.ocupancyValues[count]:self.ctrlNotes(x,u"Notes occupation"), padx=4, pady=1)
				myNotes.pack(side=RIGHT)
				self.balloon.bind(myNotes, u"Détails de la note")
			else: 
				Entry(f, textvariable=self.ocupancyValues[count], width=23).pack(side=LEFT, fill=X)
			f.pack(side=TOP, fill=X)
			count += 1
		# Boutons enregistrement (new ou modify) et suppression
		s = Frame(leftFrame) 
		self.saveOcupancyBt=Button(s, image=self.imgSave, command=self.createOcupancy)
		self.saveOcupancyBt.bind("<Return>", self.createOcupancy)
		self.saveOcupancyBt.pack(side=LEFT)
		self.balloon.bind(self.saveOcupancyBt, u"Enregistrer")
		self.deleteOcupancyBt=Button(s, image=self.imgDelete, command=self.deleteOcupancy, state=DISABLED)
		self.deleteOcupancyBt.bind("<Return>", self.deleteOcupancy)
		self.deleteOcupancyBt.pack(side=LEFT)
		self.balloon.bind(self.deleteOcupancyBt, u"Supprimer")
		s.pack(side=TOP, fill=X)
		leftFrame.pack(side=LEFT, fill=X)
		# Liste des Occupation existants (présentation colonne de droite)
		rightFrame = Frame(self) 
		Label(rightFrame, text=u"Liste des Occupations").pack(side=TOP, fill=X)
		self.searchOcupancyValue = StringVar()
		self.searchOcupancyEt = Entry(rightFrame,  width=83, textvariable=self.searchOcupancyValue, relief=GROOVE)
		self.searchOcupancyEt.bind("<KeyRelease>", self.searchOcupancy)
		self.searchOcupancyEt.pack(side=TOP, fill=X)
		self.balloon.bind(self.searchOcupancyEt, u"Saisir les premières lettres d'une Résidence\npour une recherche plus précise,\nla liste est classée par Résidence.")
		s = Frame(rightFrame) 
		scrollbar = Scrollbar(s)
		scrollbar.pack(side=RIGHT, fill=Y)
		self.listOcupancy = Listbox(s)
		self.listOcupancy.config(yscrollcommand=scrollbar.set, width=80, selectmode=SINGLE, height=17)
		self.listOcupancy.bind("<ButtonRelease-1>",self.selectOcupancy)
		scrollbar.config(command=self.listOcupancy.yview)
		self.listOcupancy.pack()
		self.balloon.bind(self.listOcupancy, u"Séléctionner un Séjour\npour la visualiser ou la modifier.")
		s.pack(side=TOP, fill=X)
		rightFrame.pack(side=RIGHT, fill=BOTH)
		# Initialisation
		self.clearFieldOcupancy()
		self.searchOcupancy()

	def ctrlTimeNow1(self,event):
		varHour=[self.ocupancyHourIn, self.ocupancyMinuteIn, self.hourInOcupancyCB, self.minInOcupancyCB] 
		TimePopupGUI(self, event=event, field=self.ocupancyValues[4], varHour=varHour, log=self.log, path=self.path)

	def ctrlTimeNow2(self,event):
		varHour=[self.ocupancyHourOut, self.ocupancyMinuteOut, self.hourOutOcupancyCB, self.minOutOcupancyCB]
		TimePopupGUI(self, event=event, field=self.ocupancyValues[10], varHour=varHour, log=self.log, path=self.path)

	def ctrlCalendar(self,field):
		CalendarGUI(field=field, log=self.log, path=self.path)

	def ctrlNotes(self,field,title):
		NotesGUI(field=field,title=title, log=self.log, path=self.path)

	def ctrlListPlace(self,field):
		PlaceListGUI(balloon=self.balloon, field=field, index=0, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListStay(self,field):
		StayListGUI(balloon=self.balloon, field=field, index=1, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListProduct(self,field):
		ProductListGUI(balloon=self.balloon, field=field, index=2, indexPlace=0, listObject=self.listObject, log=self.log, path=self.path)

	def ctrlListStaff(self,field,index):
		StaffListGUI(balloon=self.balloon, field=field, index=index, listObject=self.listObject, log=self.log, path=self.path)

	def ocupancyHourIn(self, value):
		self.ocupancyHourIn.set(value)
		self.minInOcupancyCB.selectitem(0)
		self.minInOcupancyCB.invoke()

	def ocupancyMinuteIn(self, value):
		self.ocupancyMinuteIn.set(value)

	def ocupancyHourOut(self, value):
		self.ocupancyHourOut.set(value)
		self.minOutOcupancyCB.selectitem(0)
		self.minOutOcupancyCB.invoke()

	def ocupancyMinuteOut(self, value):
		self.ocupancyMinuteOut.set(value)

	def getDateTimeInOcupancy(self):
		if self.ocupancyValues[3].get() != "":
			date=self.ocupancyValues[3].get().split("/")
			d = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.ocupancyHourIn.get()), int(self.ocupancyMinuteIn.get()), 0)
			return d
		else:
			return None

	def getDateTimeOutOcupancy(self):
		if self.ocupancyValues[9].get() != "":
			date=self.ocupancyValues[9].get().split("/")
			d = datetime.datetime(int(date[2]), int(date[1]), int(date[0]), int(self.ocupancyHourOut.get()), int(self.ocupancyMinuteOut.get()), 0)
			return d
		else:
			return None

	def verifyOcupancy(self):
		if self.ocupancyValues[0].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Résidence est obligatoire !\nMerci de le compléter.")
			return False
		elif self.ocupancyValues[1].get() == "":
			showerror(u"Erreur de saisie", u"Le champ Séjour associé est obligatoire !\nMerci de le compléter.")
			return False
		elif self.ocupancyValues[2].get() == "": 
			showerror(u"Erreur de saisie", u"Le champ Produit est obligatoire !\nMerci de le compléter.")
			return False
		else:
			return True

	def createOcupancy(self, event=None):
		if self.verifyOcupancy():
			if  self.deleteOcupancyBt.config()["state"][4] == "normal":
				self.modifyOcupancy()
			else:
				if askyesno(u"Enregistrement", u"Souhaitez-vous enregistrer %s comme un nouveau Ocupancy ?\n" % self.ocupancyValues[0].get()):
					Ocupancy(place=self.listObject[0],
						stay=self.listObject[1],
						product=self.listObject[2],
						checkIn=self.getDateTimeInOcupancy(),
						checkOut=self.getDateTimeOutOcupancy(),
						checkInBy=self.listObject[3],
						checkOutBy=self.listObject[4],
						invantoryInBy=self.listObject[5],
						invantoryOutBy=self.listObject[6],
						notes=self.ocupancyValues[11].get().encode("utf-8"),
						createDate=datetime.datetime.now()
					)
					self.searchOcupancy()
				self.clearFieldOcupancy()

	def modifyOcupancy(self, event=None): 
		if askyesno(u"Modifier", u"Souhaitez-vous modifier le Ocupancy %s ?" % self.selectedOcupancy.id):
			self.selectedOcupancy.place=self.listObject[0]
			self.selectedOcupancy.stay=self.listObject[1]
			self.selectedOcupancy.product=self.listObject[2]
			self.selectedOcupancy.checkIn=self.getDateTimeInOcupancy()
			self.selectedOcupancy.checkOut=self.getDateTimeOutOcupancy()
			self.selectedOcupancy.checkInBy=self.listObject[3]
			self.selectedOcupancy.checkOutBy=self.listObject[4]
			self.selectedOcupancy.invantoryInBy=self.listObject[5]
			self.selectedOcupancy.invantoryOutBy=self.listObject[6]
			self.selectedOcupancy.notes=self.ocupancyValues[11].get().encode("utf-8")
			self.searchOcupancy()
		self.deleteOcupancyBt.config(state=DISABLED)
		self.clearFieldOcupancy()

	def deleteOcupancy(self, event=None): 
		if askyesno(u"Suppression", u"Souhaitez-vous supprimer le Ocupancy %s ?\nCette opération est irréversible !" % self.selectedOcupancy.id):
			Ocupancy.delete(self.selectedOcupancy.id)
			self.searchOcupancy()            
		self.deleteOcupancyBt.config(state=DISABLED)
		self.clearFieldOcupancy()
	# FIN de la gestion du module Ocupancy ----------------------------------------------------------------------------------------------------------------

#~ class OcupancyListGUI(Toplevel):
    #~ def __init__(self, parent=None, balloon=None, field=None, index=None):
        #~ Toplevel.__init__(self, parent)
        #~ self.parent=parent
        #~ self.grab_set()
        #~ self.transient(self.master)
        #~ self.resizable(width=False, height=False)
        #~ self.title(u"Liste des Articles")
        #~ self.balloon=balloon
        #~ self.field=field
        #~ self.index=index
        #~ self.makeListItem()